package com.example.controller;

import com.example.service.MqttIntegrationService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/mqtt")
public class MqttIntegrationController {

    @Autowired
    private MqttIntegrationService mqttIntegrationService;

    /**
     * 发布消息
     */
    @PostMapping("/publish")
    public String publishMessage(@RequestBody PublishRequest request) {
        mqttIntegrationService.publishMessage(request.getTopic(), request.getMessage());
        return "消息发布成功";
    }

    /**
     * 发布传感器数据
     */
    @PostMapping("/sensor")
    public String publishSensorData(@RequestBody SensorDataRequest request) {
        String message = String.format("{\"temperature\": %.1f, \"humidity\": %.1f, \"timestamp\": \"%s\"}",
            request.getTemperature(), request.getHumidity(), request.getTimestamp());
        mqttIntegrationService.publishMessage("sensor/data", message);
        return "传感器数据发布成功";
    }

    /**
     * 发布设备状态
     */
    @PostMapping("/device/checkStatus")
    public String publishDeviceStatus(@RequestBody DeviceStatusRequest request) {
        String message = String.format("{\"deviceId\": \"%s\", \"status\": \"%s\", \"timestamp\": \"%s\"}",
            request.getDeviceId(), request.getStatus(), request.getTimestamp());
        mqttIntegrationService.publishMessage("device/checkStatus", message);
        return "设备状态发布成功";
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public String health() {
        return "Spring Integration MQTT服务运行正常";
    }

    @Data
    public static class PublishRequest {
        private String topic;
        private String message;
    }

    @Data
    public static class SensorDataRequest {
        private double temperature;
        private double humidity;
        private String timestamp;
    }

    @Data
    public static class DeviceStatusRequest {
        private String deviceId;
        private String status;
        private String timestamp;
    }
}
